import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import DashboardView from '../views/DashboardView.vue'
import ProductsView from '../views/ProductsView.vue'
import CategoriesView from '../views/CategoriesView.vue'
import { useUserStore } from '@/stores/user.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
   
    {
      path: '/dashboard',
      name: 'dashboard',
      component: DashboardView,
      meta: { requiresAuth: true, title: '控制台' }
    },
    {
      path: '/products',
      name: 'products',
      component: ProductsView,
      meta: { requiresAuth: true, title: '商品管理' }
    },
    {
      path: '/categories',
      name: 'categories',
      component: CategoriesView,
      meta: { requiresAuth: true, title: '分类管理' }
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
      meta: { requiresAuth: true, title: '关于' }
    },
    {
      path: '/',
      name: 'login',
      component: LoginView,
      meta: { title: '管理员登录' }
    }
  ],
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 微信商城后台管理系统` : '微信商城后台管理系统'
  
  // 检查路由是否需要授权
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 获取用户存储
    const userStore = useUserStore()
    
    // 检查用户是否已登录
    if (!userStore.loggedIn) {
      // 用户未登录，重定向到登录页面
      next({ name: 'login' })
    } else {
      // 检查管理员状态
      if (userStore.admin?.status === 'inactive') {
        // 账号已禁用，清除登录信息
        userStore.logout()
        // 重定向到登录页面并显示错误信息
        next({ 
          name: 'login', 
          params: { error: 'account_disabled', message: '账号已被禁用，请联系管理员' } 
        })
      } else {
        // 用户已登录且状态正常，继续导航
        next()
      }
    }
  } else {
    // 如果访问的是根路径，且用户已登录，重定向到仪表盘
    if (to.path === '/' && useUserStore().loggedIn) {
      next({ name: 'dashboard' })
    } else {
      // 不需要授权的路由，直接放行
      next()
    }
  }
})

export default router
